#include "columnwidget.h"
#include "ui_columnwidget.h"
#include <QMessageBox>
#include <QDebug>

ColumnWidget::ColumnWidget(const ColumnCollection &columns_, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ColumnWidget)
{
    ui->setupUi(this);

    this->columns = &columns_;

    // Set up connection between data changes and UI

    connect(this, SIGNAL(addColumnRequested(Column,QString)),
            columns, SLOT(add(Column,QString)));
    connect(this, SIGNAL(updateColumnRequested(QString,Column,QString)),
            columns, SLOT(update(QString,Column,QString)));
    connect(this, SIGNAL(removeColumnRequested(QString)), columns,
            SLOT(remove(QString)));

    connect(columns, SIGNAL(columnAdded(Column,QString)), this,
            SLOT(addColumn(Column,QString)));
    connect(columns, SIGNAL(columnUpdated(QString,Column,QString)),
            this, SLOT(updateColumn(QString,Column,QString)));
    connect(columns, SIGNAL(columnRemoved(QString)), this,
            SLOT(removeColumn(QString)));

    connect(columns, SIGNAL(cleared()), this, SLOT(clearAll()));
}

ColumnWidget::~ColumnWidget()
{
    delete ui;
}

void ColumnWidget::clearColumnForm() {
    ui->colName->setText("");
    ui->colDefaultValue->setText("");
    ui->colDefaultValueAs->setText("");
    ui->colVisible->setChecked(true);
    ui->colKey->setText("");
}

QList<KeyPair<Column> > ColumnWidget::getOrderedColumns() {
    QList<KeyPair<Column> > list;
    for(int i = 0; i<ui->colList->count(); ++i) {
        QString key = ui->colList->item(i)->data(Qt::UserRole).toString();
        list.append(KeyPair<Column>(key, columns->get(key)));
    }
    return list;
}

void ColumnWidget::on_colList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(current){
        QString key = current->data(Qt::UserRole).toString();
        if(columns->contains(key)) {
            Column column = columns->get(key);
            ui->colName->setText(column.getName());
            ui->colDefaultValue->setText(column.defaultValue);
            ui->colDefaultValueAs->setText(column.defaultValueAs);
            ui->colVisible->setEnabled(column.visible);
            ui->colKey->setText(key);
            ui->colDelete->setEnabled(true);
            ui->colUpdate->setEnabled(true);
        } else {
            qDebug() << "The ID does not exist in columns";
            ui->colDelete->setEnabled(false);
            ui->colUpdate->setEnabled(false);
            clearColumnForm();
        }
    } else {
        ui->colDelete->setEnabled(false);
        ui->colUpdate->setEnabled(false);
        clearColumnForm();
    }
}

void ColumnWidget::on_colAdd_clicked()
{
    Column column(ui->colName->text(), ui->colDefaultValue->text(),
                  ui->colDefaultValueAs->text(), ui->colVisible->isChecked());
    emit addColumnRequested(column, ui->colKey->text());
}

void ColumnWidget::on_colUpdate_clicked()
{
    Column column(ui->colName->text(), ui->colDefaultValue->text(),
                  ui->colDefaultValueAs->text(), ui->colVisible->isChecked());
    QString oldKey = ui->colList->currentItem()->data(Qt::UserRole).toString();
    emit updateColumnRequested(oldKey, column, ui->colKey->text());
}

void ColumnWidget::on_colDelete_clicked()
{
    if(QMessageBox::warning(0, tr("Are you sure?"), tr("Deleting a column will make invalid all values that use it. Are you sure you want to continue?"),
                            QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
        emit removeColumnRequested(ui->colList->currentItem()->data(Qt::UserRole).toString());
}

void ColumnWidget::addColumn(const Column &column, const QString &key) {
    Q_ASSERT_X(!keyIndex.contains(key), "ColumnWidget::addColumn()", "Attempting to replace existing element");
    QListWidgetItem *item = new QListWidgetItem(column.getName());
    item->setData(Qt::UserRole, key);
    ui->colList->addItem(item);
    keyIndex.insert(key, item);
    clearColumnForm();
}

void ColumnWidget::updateColumn(const QString &oldKey, const Column &newColumn,
                                const QString &newKey) {
    QListWidgetItem *item = keyIndex.value(oldKey, NULL);
    if(item) {
        item->setText(newColumn.getName());
        if(oldKey != newKey) {
            item->setData(Qt::UserRole, QVariant(newKey));
            Q_ASSERT_X(!keyIndex.contains(newKey), "When updating column in ColumnWidget", "Attempting to overwrite another item");
            keyIndex.remove(oldKey);
            keyIndex.insert(newKey, item);
        }
    }
}

void ColumnWidget::removeColumn(const QString &key) {
    QListWidgetItem *item = keyIndex.value(key, NULL);
    if(item) {
        delete item;
        keyIndex.remove(key);
    }
}

void ColumnWidget::clearAll() {
    ui->colList->clear();
    keyIndex.clear();
    clearColumnForm();
}

void ColumnWidget::changeEvent(QEvent *event) {
    if(event->type() == QEvent::LanguageChange)
        ui->retranslateUi(this);
    QWidget::changeEvent(event);
}
